﻿var _SERVER_ = 'http://localhost/'

var Inject = (function (){
	var received_data = {};

	// constants ----------------------------------------------------------------
	var ID = {
		IFRAME_PREFIX	: 'WC-iframe-'
	};
	
	var areas_rect = {};
	
	// variables ----------------------------------------------------------------
	var _this		= {},
		_views		= {};
	
	// initialize ---------------------------------------------------------------
	_this.init = function (){
	
		div_dialog = $('<div id="dialog_web_collector" \
							 style="display:none;" \
							 title="WebCollector Gerar Código"> \
							 <p id="content_dialog"></p>  \
						</div> ');
		$(document.body).append(div_dialog);
		
		// add the wc_generator_index iframe
		getView('wc_generator_index');

		// listen to the iframes/webpages message
		window.addEventListener("message", dom_onMessage, false);
	
		// listen to the Control Center (background.js) messages
		chrome.extension.onMessage.addListener(background_onMessage);
		
		window.WB_AREA_NEXT_ID = 0;
		window.select_area = false;
		window.select_component = false;
		window.select_area_started = false;
		var x1, x2, y1, y2;
		$(document).mousedown(function(e) {
			if(window.select_area){
				box_area = $('<div class="gray_transparent" id="current_box_area" style="border:1px black solid; z-index:1000002; position:absolute;">');
				$(document.body).append(box_area);
				x1 = e.pageX;
				y1 = e.pageY;
				$('#current_box_area').css({
						 top: y1 , //offsets
						 left: x1  //offsets
				});
				window.select_area_started = true;
			}
		});
		
		/*$(document).on("mouseenter", "*", function(e){
			
		});*/
		
		$(document).on({
			mouseenter: function () {
				if(window.select_component){
					console.log($(this));
					$(".add_component").stop().animate(true, false).removeClass("add_component", {duration:500});
					$(this).stop().animate(true, false).addClass("add_component inside", {duration:500});
				}
			},

			mouseleave: function () {
				if(window.select_component){
					$(this).stop().animate(true, false).removeClass("add_component inside", {duration:500});
					if($(this).parent().hasClass("inside")){
						$(this).parent().stop().animate(true, false).addClass("add_component", {duration:500});
					}
				}
			}
		}, '*');
		
		function HitTest()
		{	
			for(r2 in areas_rect){
				if($("#current_box_area").collision("#"+r2).length){
					$('#current_box_area').css({
							   width: Math.abs($('#current_box_area').width() - 1), //offsets
							   height: Math.abs($('#current_box_area').height() - 1) //offsets
							});
					return true;
				}
			}
			return false;
		}

		$(document).mousemove(function(e) {
			if(window.select_area_started){
			
				var offset = $('#current_box_area').offset();
				var left = offset.left;
				var top = offset.top;
				var width = $('#current_box_area').width();
				var height = $('#current_box_area').height();
			
						
				x2 = e.pageX;
				y2 = e.pageY;
				if(x2 >= x1 && y2 >= y1){
					if(x2 < $( document ).width() && y2 < $( document ).height()){
						$('#current_box_area').css({
						   width: Math.abs(x2 - x1), //offsets
						   height: Math.abs(y2 - y1) //offsets
						});
					}
					else{
						if(x2 < $( document ).width()){
							$('#current_box_area').css({
								width: Math.abs(x2 - x1) //offsets
							});
						}
						
						if(y2 < $( document ).height()){
							$('#current_box_area').css({
								height: Math.abs(y2 - y1) //offsets
							});
						}
					}
				}
				else{
					
					if(x2 < x1){
						$('#current_box_area').css({
							left: x2,	
							width: Math.abs(x1 - x2), //offsets
						});
					}else{
						$('#current_box_area').css({
							left: x1, 
							width: Math.abs(x2 - x1), //offsets
						});
					}
					
					if(y2 < y1){
						$('#current_box_area').css({
							top: y2,
							height: Math.abs(y1 - y2), //offsets
						});
					}
					else{
						$('#current_box_area').css({
							top: y1, 
							height: Math.abs(y2 - y1), //offsets
						});
					}

				}
				
				if(HitTest()){	
					$('#current_box_area').css({
						top: top,
						left: left,
						width: width,
						height: height
					});
				}
			}	
		});

		$(document).mouseup(function() {
			if(window.select_area) {
				console.log("MOUSE UP");

				window.select_area = false;
				window.select_area_started = false;
				$('#current_box_area').attr('id', 'WC_AREA_'+window.WB_AREA_NEXT_ID);
				
				
				
				var top = 0, left = 0, bottom = 0, right = 0;
				if(x2 > x1){
					right = x2;
					left = x1;
				}
				else{
					right = x1;
					left = x2;
				}
				
				if(y2 > y1){
					top = y1;
					bottom = y2;
				}
				else{
					top = y2;
					bottom = y1;
				}
				
				areas_rect["WC_AREA_"+window.WB_AREA_NEXT_ID] = {right:right, top:top, bottom:bottom, left:left};
				
				tell('ADD_AREA', { 
								   view:'wc_generator_index', 
								   id:"WC_AREA_"+window.WB_AREA_NEXT_ID,
								   top: top,
								   left: left,
								   width: right-left,
								   height: bottom-top
								 });
				
				window.WB_AREA_NEXT_ID++;
				
				message_onToggleIframe();
			}
		});
		
		$(document).on("click", ".add_component", function() {
			if(window.select_component){
				event.preventDefault();
				$this = $(this);
				$(this).stop().animate(true, false).removeClass("add_component inside", {duration:500}).addClass("addedComponent");
				window.select_component = false;
				
				var width =$(this).width();
				var height =$(this).height();
				var offset = $(this).offset();
				var left = offset.left;
				var top = offset.top;
				
				areas_rect["WC_AREA_"+window.WB_AREA_NEXT_ID] = {right:left+width, top:top, bottom:top+height, left:left};
				var box_area = $('<div class="gray_transparent" id="WC_AREA_'+window.WB_AREA_NEXT_ID+'" style="border:1px black solid; z-index:1000002; position:absolute;">');
				$(document.body).append(box_area);
				$('#WC_AREA_'+window.WB_AREA_NEXT_ID).css({
						top: top,
						left: left,
						width: width,
						height: height
					});
				tell('ADD_AREA', { 
								   view:'wc_generator_index', 
								   id:"WC_AREA_"+window.WB_AREA_NEXT_ID,
								   top: top,
								   left: left,
								   width: width,
								   height: height
								 });
				window.WB_AREA_NEXT_ID++
				message_onToggleIframe();
			}
		});	
	}
	
	// private functions --------------------------------------------------------
	function getView (id){
		// return the view if it's already created
		if (_views[id]) return _views[id];
		
		// iframe initial details
		var src		= chrome.extension.getURL('html/iframe/'+id+'.html?view='+id+'&_'+(new Date().getTime())),
			iframe	= $('<iframe />', {id:ID.IFRAME_PREFIX+id, 
									   src:src, 
									   scrolling:false,
									   style: "height: 1000003%; position: fixed; right: 0px; top: 0px; background-color: black; z-index:1000003; display:none;"});
		
		// view
		_views[id] = {
			isLoaded	: false,
			iframe		: iframe
		};
		
		// add to the container
		iframe.appendTo(document.body);
		
		return _views[id];
	};
	
	function tell (message, data){
		var data = data || {};
		
		// send a message to "background.js"
		chrome.extension.sendRequest({
			message : message,
			data	: data
		});
	};
	
	function processMessage (request){
		if (!request.message) return;
		
		console.log("received message "+request.message);
		switch (request.message){
			case 'iframe-loaded': message_onIframeLoaded(request.data); break;
			case 'toggle_iframe_wc': message_onToggleIframe(); break;
			case 'ADD_AREA': message_onAddArea(); break;
			case 'hide_area': message_onToggleArea(request.data.id, request.data.toggle); break;
			case 'remove_area': message_removeArea(request.data.id); break;
			case 'hilight_area': message_highlightArea(request.data.id); break;
			case 'ADD_COMPONENT': message_onAddComponent(); break;
			case 'generate_code': message_onGenerateCode(request.data); break;
			case 'add_url': message_onAddUrl(); break;		
		}
	};
	
	// events -------------------------------------------------------------------	
	// messages coming from iframes and the current webpage
	function dom_onMessage (event){		
		if (!event.data.message) return;
		
		// tell another iframe a message
		if (event.data.view){
			tell(event.data);
		}else{
			processMessage(event.data);
		}
	};
	
	// messages coming from "background.js"
	function background_onMessage (request, sender, sendResponse){
		if (request.data.view) return;		
		processMessage(request);
	};
	
	// messages -----------------------------------------------------------------
	function message_onIframeLoaded (data){
		var view = getView(data.source), allLoaded	= true;
		
		view.isLoaded = true;
		
		for (var i in _views){
			if (_views[i].isLoaded === false) allLoaded = false;
		}
		
		// tell "background.js" that all the frames are loaded
		if (allLoaded) tell('all-iframes-loaded');
	};
	
	function message_onToggleIframe(){
		getView("wc_generator_index").iframe.toggle();
	}
	
	function message_onAddArea(){
		window.select_area = true;
	}
	
	function message_onToggleArea(id, toggle){
		if(toggle){
			$("#"+id).show();
		}
		else{
			$("#"+id).hide();
		}
	}
	
	function message_onAddComponent(){
		window.select_component = true;
		$(document).addClass("inside");
		$(document.body).addClass("inside");
	}
	
	function message_removeArea(id){
		console.log("REMOVED");
		$("#"+id).remove();
		delete areas_rect[id];
	}
	
	function message_highlightArea(id){
		$("#"+id).toggleClass("gray_transparent");
		$("#"+id).toggleClass("blue_transparent");
	}
	
	function gera_codigo()
	{
		var object_to_send = {}
		object_to_send['type_files'] = $('input[name=type_files]:checked', '#content_dialog').val();
		$('input[type="checkbox"][name="url_to_generate"]', '#content_dialog').each(function(){
			var status = $(this).is(':checked');
			if(!status){
				delete received_data[$(this).val()];
			}
		});
		
		object_to_send['data'] = received_data;
		
		console.log("enviando...");
		console.log(object_to_send);
		
		$.ajax({
			type: "POST",
			url: _SERVER_+"generate_file.php",
			context: document.body,
			data: { 'DATA': object_to_send }
		}).done(function(msg) {
			console.log(msg);
			var a = document.createElement('a');
			a.href = _SERVER_+msg;
			var res = msg.split("/");
			a.download = res[res.length-1]; // Filename
			a.click();
		});
	}
	
	function message_onGenerateCode(data){
		$(function() {
			
			d = $( "#dialog_web_collector" ).dialog({
				resizable: false,
				draggable: false,
				width: 500,
				maxHeight: 500,
				modal: true,
				buttons: {
					"Confirmar": function() {
					  gera_codigo();
					  $( this ).dialog( "close" );
					},
					"Cancelar": function() {
					  $( this ).dialog( "close" );
					}
			    },
			    position: "center",
				autoOpen: false,
				create: function(event, ui){
					$('.ui-dialog').wrap('<div class="ui_web_collector" />');
				},
				open: function(event, ui){
					$('.ui-widget-overlay').wrap('<div class="ui_web_collector" />');
					$(this).dialog("open");
				},
				close: function(event, ui){
					$(".ui_web_collector").filter(function(){
						if ($(this).text() == "")
						{
							return true;
						}
						return false;
					}).remove();
				}
			});
			
			d.dialog('open');
		});
		
		received_data = data;
		
		content = '<input type="radio" name="type_files" value="one_file" checked>Arquívo único';
		content += '<input type="radio" name="type_files" value="multiple_files">Vários arquivos'
		content += '<table>';
		for(i in data){
			content += '<tr>';
			content += '<td> \
							<input type="checkbox" name="url_to_generate" value="'+i+'" checked="true"> \
						</td>';
			content += '<td><div style="width:400px; overflow:hidden;">'+i+'</div></td>';
			content += '</tr>';
		}
		content += '</table>';
		
		
		$("#content_dialog").empty().html(content);
		
	}
	
	function message_onAddUrl(data){
		tell("add_url", {url:window.location.href, title:document.title});
		tell('add_url_frame', {view:'wc_generator_index', url:window.location.href});
	}
	
	return _this;
}());
document.addEventListener("DOMContentLoaded", function (){ Inject.init(); }, false);
